package com.tanhua.server.interceptor;

import com.tanhua.server.pojo.User;
import com.tanhua.server.service.UserService;
import com.tanhua.server.utils.NoAuthorization;
import com.tanhua.server.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一完成根据token查询用User的功能
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod))
            return true;
        if (((HandlerMethod)handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }
        try {
            User user = userService.queryUserByToken(request.getHeader("Authorization"));
            if (user == null)
                return false;
            UserThreadLocal.set(user);
            try {
                //发送用户操作的消息
                Map<String, Object> msg = new HashMap<>();
                msg.put("userId", user.getId());
                msg.put("date", System.currentTimeMillis());
                msg.put("type", 2);
                this.rocketMQTemplate.convertAndSend("user-sso-operate", msg);
            } catch (MessagingException e) {
                log.error("发送消息失败！", e);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //请求头中如不存在Authorization直接返回false
        response.setStatus(401); //无权限访问
        return false;
    }
}
